package com.ywps.vaas.framework.util

import com.mchange.v2.c3p0.ComboPooledDataSource
import com.ywps.vaas.framework.conf.ConfigTools
import com.ywps.vaas.framework.constant.PropertiesConstant

import java.sql.Connection

object MysqlPoolManager {
  var mysqlManager: MysqlPool = _

  /**
   * 获取连接池
   * @return
   */
  def getMysqlManager: MysqlPool = {
    synchronized {
      if (mysqlManager == null) {
        mysqlManager = new MysqlPool
      }
    }
    mysqlManager
  }


  class MysqlPool extends Serializable {
    private val cpds: ComboPooledDataSource = new ComboPooledDataSource(true)
    try {
      cpds.setUser(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_USERNAME).toString)
      cpds.setPassword(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_PASSWORD).toString)
      cpds.setJdbcUrl(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_URL).toString)
      cpds.setDriverClass(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_DRIVERCLASS).toString)
      cpds.setMinPoolSize(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_MINPOOLSIZE).toString.toInt)
      cpds.setMaxPoolSize(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_MAXPOOLSIZE).toString.toInt)
      cpds.setAcquireIncrement(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_ACQUIREINCREMENT).toString.toInt)
      cpds.setMaxStatements(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_MAXSTATEMENTS).toString.toInt)
      cpds.setInitialPoolSize(ConfigTools.getPropertiesFactory.get(PropertiesConstant.MYSQL_POOL_JDBC_INITIALPOOLSIZE).toString.toInt)

    } catch {
      case e: Exception => e.printStackTrace
      case e: NullPointerException => e.printStackTrace
    }

    def getConnection: Connection = {
      try {
        cpds.getConnection
      } catch {
        case ex: Exception =>
          ex.printStackTrace
          null
      }
    }

    def getConnection(databaseName:String): Connection = {
      try {
        if(databaseName.nonEmpty && !"".equals(databaseName.trim)){
          val preUrl: String = cpds.getJdbcUrl
          val i: Int = preUrl.lastIndexOf("/").intValue()
          val j: Int = preUrl.indexOf("?").intValue()
          val start: String = preUrl.substring(0, i + 1)
          val end: String = preUrl.substring(j, preUrl.length)
          val realUrl: String = start+databaseName+end
          cpds.setJdbcUrl(realUrl)
          cpds.getConnection
        }else{
          cpds.getConnection
        }

      } catch {
        case ex: Exception =>
          ex.printStackTrace
          null
      }
    }

    def close(): Unit = {
      try {
        cpds.close()
      } catch {
        case ex: Exception =>
          ex.printStackTrace
      }
    }
  }
}
